package gov.pbc.nn.kjgl.fxq.organInfor.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.core.dao.CommonJdbcDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;
import gov.pbc.nn.core.entity.BaseEntity;
import gov.pbc.nn.kjgl.fxq.attachment.AttachmentDao;
import gov.pbc.nn.kjgl.fxq.attachment.AttachmentEntity;
import gov.pbc.nn.kjgl.fxq.organInfor.entity.*;
import gov.pbc.nn.kjgl.maintenance.entity.SysEmergencyPlan;
import gov.pbc.nn.kjgl.maintenance.entity.SysEmergencyPlanDept;
import gov.pbc.nn.kjgl.maintenance.entity.SysEmergencyPlanHeader;

import org.h2.command.dml.Delete;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.bdf2.core.service.IDeptService;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.core.Configure;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.uploader.DownloadFile;
import com.bstek.dorado.uploader.UploadFile;
import com.bstek.dorado.uploader.annotation.FileProvider;
import com.bstek.dorado.uploader.annotation.FileResolver;
import com.bstek.dorado.uploader.util.ParameterUtils;

@Component
public class OrganInforPR {
	
	@Resource(name = CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao hibernateDao;
	

	@Resource(name = CommonJdbcDao.BEAN_ID)
	private CommonJdbcDao jdbcDao;
	
	@Autowired
	@Qualifier(IDeptService.BEAN_ID)
	private IDeptService deptService;
	

   /*-----------------------DataProvider-----------------------*/
	
	@DataProvider
	public void loadOrgan(Page<OrganInfor> page, Criteria criteria) {
		IUser user= ContextHolder.getLoginUser();
		if(user==null)
			throw new NoneLoginException("请先登录！");
		if(user.getDepts()==null||user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept=(Dept) user.getDepts().get(0);
		System.out.println(dept.getName());
		List<IDept> children= deptService.loadDeptsByParentId(dept.getParentId(), dept.getCompanyId());
		List<String> childrenIds=new ArrayList<String>();
		for (IDept child : children) {

			childrenIds.add(child.getId());
		}
		childrenIds.add(dept.getCDept().getId());
		DetachedCriteria query = this.hibernateDao.buildDetachedCriteria(criteria, OrganInfor.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.in("deptId", childrenIds));
		query.addOrder(Order.desc("createDate"));
		this.hibernateDao.pagingQuery(page, query);
	}

	
	@DataProvider
	public void loadOrganPersonInfor(Page<OrganPersonInfor> page, Criteria criteria,String organInforId) {
		DetachedCriteria query = this.hibernateDao.buildDetachedCriteria(criteria, OrganPersonInfor.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("organInforId", organInforId));
		query.addOrder(Order.asc("state")).addOrder(Order.asc("personNum")).addOrder(Order.asc("personType")).addOrder(Order.desc("createDate"));;
		this.hibernateDao.pagingQuery(page, query);
	}
	
	@DataProvider
	public List<OrganInforModify> loadOrganInforModify(String organInforId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(OrganInforModify.class);
		criteria.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		criteria.add(Restrictions.eq("organId", organInforId));
		criteria.addOrder(Order.desc("createDate"));
		List<OrganInforModify> values = (List<OrganInforModify>) this.hibernateDao.query(criteria);
		if (!values.isEmpty()) {
			return values;
		}
		return null;
	}
	
	@DataProvider
	public List<AttachmentEntity> loadAttachmentEntity(String organInforId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(AttachmentEntity.class);
		criteria.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		criteria.add(Restrictions.eq("fxqEntityId", organInforId));
		criteria.addOrder(Order.desc("createDate"));
		List<AttachmentEntity> values = (List<AttachmentEntity>) this.hibernateDao.query(criteria);
		if (!values.isEmpty()) {
			return values;
		}
		return null;
	}
	/*-----------------------DataResolver-----------------------*/
	@Transactional
	@DataResolver
	public void saveOrgan(Collection<OrganInfor> organInfors) throws Exception
	{

		IUser user= ContextHolder.getLoginUser();
		if(user==null)
			throw new NoneLoginException("请先登录！");
		if(user.getDepts()==null||user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept=(Dept) user.getDepts().get(0);
		for (OrganInfor organInfor : organInfors) {

			if (EntityUtils.getState(organInfor).equals(EntityState.NEW)) {
				//organInfor.setCreateDate(new Date());
				organInfor.setDeptId(dept.getCDept().getId());
				organInfor.setDeptName(dept.getCDept().getName());
				//this.saveOrganInforNew(organInfor);
				this.hibernateDao.save(organInfor);
			} else if (EntityUtils.getState(organInfor).equals(EntityState.MODIFIED)) {
				this.saveOrganInforModify(organInfor);
				this.hibernateDao.update(organInfor);
			} else if (EntityUtils.getState(organInfor).equals(EntityState.DELETED)) {
				//this.saveOrganInforDelete(organInfor);
				this.hibernateDao.delete(organInfor);
			}
			List<OrganPersonInfor> organPersonInfors = EntityUtils.getValue(organInfor, "organPersonInfors");
			if (organPersonInfors != null) {
				for (OrganPersonInfor organPersonInfor : organPersonInfors) {
					if (EntityUtils.getState(organPersonInfor).equals(EntityState.NEW)) {
						organPersonInfor.setOrganInforId(organInfor.getId());
						this.saveOrganPersonInforNew(organInfor.getOrganName(),organInfor.getOrganNum(),organPersonInfor);
						this.hibernateDao.save(organPersonInfor);
					}  else if (EntityUtils.getState(organPersonInfor).equals(EntityState.MODIFIED)) {
						this.saveOrganPersonInforModify(organInfor.getOrganName(),organInfor.getOrganNum(),organPersonInfor);
						this.hibernateDao.update(organPersonInfor);
					}else if (EntityUtils.getState(organPersonInfor).equals(EntityState.DELETED)) {
						this.saveOrganPersonInforDelete(organInfor.getOrganName(),organInfor.getOrganNum(),organPersonInfor);
						this.hibernateDao.delete(organPersonInfor);
					}
				}
			}

			List<AttachmentEntity> attachments = EntityUtils.getValue(organInfor, "attachments");
			if(attachments!=null){
				for (AttachmentEntity attachment : attachments) {
					if (EntityUtils.getState(attachment).equals(EntityState.NEW)) {
						this.hibernateDao.save(attachment);
					} else if (EntityUtils.getState(attachment).equals(EntityState.MODIFIED)) {
						this.hibernateDao.update(attachment);
					} else if (EntityUtils.getState(attachment).equals(EntityState.DELETED)) {
						this.hibernateDao.delete(attachment);
					}
				}
			}
		}

	}
	
	/*public void saveOrganInforNew(OrganInfor of)
	{	
		OrganInforModify organInforModify = new OrganInforModify();
		if(of != null)
		{
			organInforModify.setOrganId(of.getId());
			organInforModify.setOrganName(of.getOrganName());
			organInforModify.setOrganNum(of.getOrganNum());
			organInforModify.setOpetateMode(1);
			organInforModify.setModifyContent("新增"+of.getOrganName()+"机构信息");
			this.hibernateDao.save(organInforModify);
		}
	}
	
	public void saveOrganInforDelete(OrganInfor of)
	{	
		OrganInforModify organInforModify = new OrganInforModify();
		if(of != null)
		{
			organInforModify.setOrganId(of.getId());
			organInforModify.setOrganName(of.getOrganName());
			organInforModify.setOrganNum(of.getOrganNum());
			organInforModify.setOpetateMode(3);
			organInforModify.setModifyContent("删除"+of.getOrganName()+"机构信息");
			this.hibernateDao.save(organInforModify);
		}
	}*/
	
	public void saveOrganInforModify(OrganInfor of)
	{	
		OrganInforModify organInforModify = new OrganInforModify();
		if(of != null)
		{

				String op = "";
	
				String oldOrganName = EntityUtils.getOldString(of, "organName");
				String oldOrganNum = EntityUtils.getOldString(of, "organNum");
				String oldFax = EntityUtils.getOldString(of, "fax");
				String oldAddress = EntityUtils.getOldString(of, "address");
				String oldZipCode = EntityUtils.getOldString(of, "zipCode");
				String oldDeptName = EntityUtils.getOldString(of, "deptName");
				int oldIndustryType = EntityUtils.getOldInt(of, "industryType");
				int oldIsLegalPerson = EntityUtils.getOldInt(of, "isLegalPerson");
				int oldIsForeignCapital = EntityUtils.getOldInt(of, "isForeignCapital");
				int oldOrganState = EntityUtils.getOldInt(of, "organState");
				String oldDepartment = EntityUtils.getOldString(of, "department");
				if(!oldOrganName.equals(of.getOrganName()))
				{
					op = op+"义务机构名称由"+oldOrganName+"变动为"+of.getOrganName()+"  ";
				}
				if(!oldOrganNum.equals(of.getOrganNum()))
				{
					op = op+"义务机构编号由"+oldOrganNum+"变动为"+of.getOrganNum()+"  ";
				}
				if(!oldFax.equals(of.getFax()))
				{
					op = op+"传真由"+oldFax+"变动为"+of.getFax()+"  ";
				}
				if(!oldAddress.equals(of.getAddress()))
				{
					op = op+"地址由"+oldAddress+"变动为"+of.getAddress()+"  ";
				}
				if(!oldZipCode.equals(of.getZipCode()))
				{
					op = op+"邮编由"+oldZipCode+"变动为"+of.getZipCode()+"  ";
				}
				if(!oldDeptName.equals(of.getDeptName()))
				{
					op = op+"所属部门由"+oldDeptName+"变动为"+of.getDeptName()+"  ";
				}
				if(oldIndustryType !=of.getIndustryType())
				{
					op = op+"行业类别由"+oldIndustryType+"变动为"+of.getIndustryType()+"  ";
				}
				if(oldIsLegalPerson != of.getIsLegalPerson())
				{
					op = op+"是否法人由"+oldIsLegalPerson+"变动为"+of.getIsLegalPerson()+"  ";
				}
				if(oldIsForeignCapital != of.getIsForeignCapital())
				{
					op = op+"是否外资由"+oldIsForeignCapital+"变动为"+of.getIsForeignCapital()+"  ";
				}
				if(oldOrganState != of.getOrganState())
				{
					op = op+"机构状态由"+oldOrganState+"变动为"+of.getOrganState()+"  ";
				}
				if(!oldDepartment.equals(of.getDepartment()))
				{
					op = op+"职能部门由"+oldDepartment+"变动为"+of.getDepartment()+"  ";
				}
				
				if(!op.equals(""))
				{
					organInforModify.setOpetateMode(2);
					organInforModify.setOrganId(of.getId());
					organInforModify.setOrganName(of.getOrganName());
					organInforModify.setOrganNum(of.getOrganNum());
					organInforModify.setModifyContent(op);
					this.hibernateDao.save(organInforModify);
				}
		}

	}
	
	public void saveOrganPersonInforNew(String organName,String organNum, OrganPersonInfor opf)
	{	
		OrganInforModify organInforModify = new OrganInforModify();
		if(opf != null)
		{
			organInforModify.setOrganId(opf.getOrganInforId());
			organInforModify.setOrganName(organName);
			organInforModify.setOrganNum(organNum);
			organInforModify.setOpetateMode(1);
			organInforModify.setModifyContent("新增"+opf.getPersonName()+"人员信息");
			this.hibernateDao.save(organInforModify);
		}
	}
	
	public void saveOrganPersonInforDelete(String organName,String organNum, OrganPersonInfor opf)
	{	
		OrganInforModify organInforModify = new OrganInforModify();
		if(opf != null)
		{
			organInforModify.setOrganId(opf.getOrganInforId());
			organInforModify.setOrganName(organName);
			organInforModify.setOrganNum(organNum);
			organInforModify.setOpetateMode(3);
			organInforModify.setModifyContent("删除"+opf.getPersonName()+"人员信息");
			this.hibernateDao.save(organInforModify);
		}
	}
	
	public void saveOrganPersonInforModify(String organName,String organNum, OrganPersonInfor opf)
	{	
		OrganInforModify organInforModify = new OrganInforModify();
		if(opf != null)
		{

				String op = "";
	

				int oldPersonType = EntityUtils.getOldInt(opf, "personType");
				int oldPersonNum = EntityUtils.getOldInt(opf, "personNum");
				int oldPersonSex = EntityUtils.getOldInt(opf, "personSex");
				int oldState = EntityUtils.getOldInt(opf, "state");
				String oldOfficePhone = EntityUtils.getOldString(opf, "officePhone");
				String oldMoblePhone = EntityUtils.getOldString(opf, "moblePhone");
				String oldPersonName = EntityUtils.getOldString(opf, "personName");
				if(!oldOfficePhone.equals(opf.getOfficePhone()))
				{
					op = op+"人员办公电话由"+oldOfficePhone+"变动为"+opf.getOfficePhone()+"  ";
				}
				if(!oldMoblePhone.equals(opf.getMoblePhone()))
				{
					op = op+"人员手机号码由"+oldMoblePhone+"变动为"+opf.getMoblePhone()+"  ";
				}
				if(!oldPersonName.equals(opf.getPersonName()))
				{
					op = op+"人员姓名由"+oldPersonName+"变动为"+opf.getPersonName()+"  ";
				}
	
				if(oldPersonType !=opf.getPersonType())
				{
					op = op+"人员类别由"+oldPersonType+"变动为"+opf.getPersonType()+"  ";
				}
				if(oldPersonNum != opf.getPersonNum ())
				{
					op = op+"人员编号由"+oldPersonNum+"变动为"+opf.getPersonNum()+"  ";
				}
				if(oldPersonSex != opf.getPersonSex())
				{
					op = op+"人员性别由"+oldPersonSex+"变动为"+opf.getPersonSex()+"  ";
				}
				if(oldState != opf.getState())
				{
					op = op+"状态由"+oldState+"变动为"+opf.getState()+"  ";
				}

				if(!op.equals(""))
				{
					organInforModify.setOpetateMode(2);
					organInforModify.setOrganId(opf.getOrganInforId());
					organInforModify.setOrganName(organName);
					organInforModify.setOrganNum(organNum);
					organInforModify.setModifyContent(op);
					this.hibernateDao.save(organInforModify);
				}
		}

	}

}
